<?php

/* Check the absolute path to the Social Auto Poster directory. */
if ( !defined( 'SAP_APP_PATH' ) ) {
    // If SAP_APP_PATH constant is not defined, perform some action, show an error, or exit the script
    // Or exit the script if required
    exit();
}

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

/**
 * Email class
 */
class Sap_Email{
	public $mailer;
	public $settings;
	public $smtp;

	// Constructor
	public function __construct() {

		// Get class
		$this->settings = new SAP_Settings();

		// Init SMTP
		$this->init_smtp();
	}

	/**
	 * Init SMTP
	 */
	public function init_smtp() {

		// Get SAP options which stored
		$smtp_setting = $this->settings->get_options('sap_smtp_setting');

		$this->smtp = isset($smtp_setting['enable']) ? $smtp_setting['enable'] : 'no';

		if ('yes' == $this->smtp && isset($smtp_setting['from_email']) && isset(($smtp_setting['host'])) && isset(($smtp_setting['port'])) && isset($smtp_setting['password'])) {

			try {
	
				$from_email = isset($smtp_setting['from_email']) ? trim($smtp_setting['from_email']) : '';
				$from_name  = isset($smtp_setting['from_name']) ? trim($smtp_setting['from_name']) : '';
				$host      = isset($smtp_setting['host']) ? trim($smtp_setting['host']) : '';
				$port      = isset($smtp_setting['port']) ? trim($smtp_setting['port']) : '';
				$username  = isset($smtp_setting['username']) ? trim($smtp_setting['username']) : '';
				$password  = isset($smtp_setting['password']) ? trim($smtp_setting['password']) : '';
	

				// Include PHPMailer
				require_once(LIB_PATH . '/PHPMailer/autoload.php');
	
				// Instantiate PHPMailer
				$this->mailer = new PHPMailer(true);
				$this->mailer->isSMTP();
	
				// SMTP Settings
				$this->mailer->SMTPDebug  = SMTP::DEBUG_OFF;
				$this->mailer->SMTPAuth   = true;
				$this->mailer->Host       = $host;
				$this->mailer->Username   = $username;
				$this->mailer->Password   = $password;
				$this->mailer->Port       = $port;
				$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
				$this->mailer->isHTML(true);
	
				// Validate email before setting "From" address
				if (filter_var($from_email, FILTER_VALIDATE_EMAIL)) {
					$this->mailer->setFrom($from_email, $from_name);
				} else {
					throw new Exception("Invalid From Email Address: " . $from_email);
				}
	
			} catch (phpmailerException $e) {
				echo "Mailer Error: " . $e->errorMessage();
				exit;
			} catch (Exception $e) {
				echo "Error: " . $e->getMessage();
				exit;
			}
		}
	}


	/**
	 * Get headers
	 */
	public function get_headers() {

		$headers = '';

		// Set content-type when sending HTML email
		$headers .= "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

		return $headers;
	}

	/**
	 * send mail
	 * use php standard mail function here,
	 * so all mail will be pass from here
	 */
	public function send( $to, $subject, $msg, $attach = array(), $args = array() ) {

		// check if nothing pass to TO email

		if( empty($to) ) return false;

		if ( 'yes' == $this->smtp ) {
			$mail = $this->smtp_send( $to, $subject, $msg, $attach, $args );
		} else {
			$mail = $this->default_send( $to, $subject, $msg, $attach, $args );
		}

		return $mail;
	}

	/**
	 * Send mail with default mail function 
	 */
	public function default_send( $to, $subject, $msg, $attach = array(), $args = array() ) {

		try {

			$headers = $this->get_headers();

			// Ensure additional parameters are passed correctly
			$additional_params = '';

			if (!empty($args['from_email'])) {

				$additional_params = '-f ' . escapeshellarg($args['from_email']);

			}

			// Send email
			$mail_sent = mail( $to, $subject, $msg, $headers, $additional_params );

			return $mail_sent;

		} catch (Exception $e) {
			return false;
		}
		return false;
	}

	/**
	 * Send mail with smtp settings
	 */
	public function smtp_send( $to, $subject, $msg, $attach = array(), $args = array() ) {

		// Get SAP options which stored
		$smtp_setting = $this->settings->get_options('sap_smtp_setting');
		$this->smtp = isset($smtp_setting['enable']) ? $smtp_setting['enable'] : 'no';
		$from_email = isset($smtp_setting['from_email']) ? trim($smtp_setting['from_email']) : '';
		$from_name  = isset($smtp_setting['from_name']) ? trim($smtp_setting['from_name']) : '';
		$host      = isset($smtp_setting['host']) ? trim($smtp_setting['host']) : '';
		$port      = isset($smtp_setting['port']) ? trim($smtp_setting['port']) : '';
		$username  = isset($smtp_setting['username']) ? trim($smtp_setting['username']) : '';
		$password  = isset($smtp_setting['password']) ? trim($smtp_setting['password']) : '';
	
		// Include PHPMailer
		require_once(LIB_PATH . '/PHPMailer/autoload.php');

		try {
	        // Initialize PHPMailer
	        $this->mailer = new PHPMailer(true);
	        $this->mailer->CharSet = 'utf-8';
	        $this->mailer->isSMTP(); // Ensure SMTP mode is enabled

	        // SMTP Configuration (Ensure these are set correctly)
	        $this->mailer->SMTPDebug  = SMTP::DEBUG_OFF;
	        $this->mailer->SMTPAuth   = true;
	        $this->mailer->Host       = $host; // Replace with actual SMTP host
	        $this->mailer->Username   = $username;
	        $this->mailer->Password   = $password;
	        $this->mailer->Port       = $port; // Common ports: 465 (SSL), 587 (TLS)
	        $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 

	        
	        if (filter_var($from_email, FILTER_VALIDATE_EMAIL)) {
	            $this->mailer->setFrom($from_email, $from_name);
	        } else {
	            throw new Exception("Invalid From Email Address: " . $from_email);
	        }

	        // Set recipient
	        if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
	            throw new Exception('Invalid email address.');
	        }
	        $this->mailer->addAddress($to);

	        // Set subject and body
	        if (empty($subject)) {
	            throw new Exception('Subject cannot be empty.');
	        }
	        $this->mailer->Subject = $subject;
	        $this->mailer->Body    = $msg;
	        $this->mailer->isHTML(true);

	        // Send email
	        if (!$this->mailer->send()) {
	            throw new Exception('Mail sending failed: ' . $this->mailer->ErrorInfo);
	        }

	        return true;

	    } catch (phpmailerException $e) {
			echo "Mailer Error: " . $e->errorMessage();
			exit;
		} catch (Exception $e) {
			echo "Error: " . $e->getMessage();
			exit;
		}

		return false;
	}

	/**
	 * Send the mailer and destroy the object
	 */
	public function mail() {
	}


	/**
	 * Destructor function
	 */
	public function __destruct() {
		// destroy class object
	}

}